package com.haople.sso.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.haople.sso.core.service.CookieService;
import com.haople.sso.core.vo.Ticket;
import com.haople.sso.web.service.UserTicketService;

@Controller
public class CookieController {

	private static final Logger logger=Logger.getLogger(CookieController.class);
	
	@Value("${expire_day}")
	private Integer expireDay; //失效天数
	
	@Value("${cookie_domains}")
	private String[] cookieDomains; //需要设置cookie的 domains
	
	@Value("${server_domains}") //本服务绑定的域名（80）
	private String[] serverDomains;
	@Autowired
	private UserTicketService userTicketService;
	
	@Autowired
	private CookieService cookieService;
	
	/**
	 * 删除cookie的方法
	 * @param userName 
	 * @param domain
	 * @param response
	 * @param request
	 */
	@RequestMapping(value="/del-cookie.js")
	public void deleteCookie(String domain,HttpServletResponse response,HttpServletRequest request){
		StringBuffer url = request.getRequestURL();
		String requestDomain = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
		PrintWriter out=null;
		try {
			out=response.getWriter();
			Cookie cookie=cookieService.delCookies(domain);
			response.addCookie(cookie);
			out.println("ok");
		} catch (Exception e) {
			logger.error("-------设置Cookie 异常-[  remoteAddr:-"+request.getRemoteAddr()+"--requestDomain:-"+requestDomain+"---domain:-"+domain+"-]--------", e);
			out.println("invalid");
		}finally{
			if(out!=null){
				out.close();
			}
		}
	}
	
	/**
	 * 用户设置cookie的方法
	 * @param userName 
	 * @param domain
	 * @param response
	 * @param request
	 */
	@RequestMapping(value="/set-cookie.js")
	public void writeCookie(String userKey,String domain,HttpServletResponse response,HttpServletRequest request){
		StringBuffer url = request.getRequestURL();
		String requestDomain = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
		PrintWriter out=null;
		try {
			out=response.getWriter();
			if(StringUtils.isEmpty(userKey)){
				logger.warn("-----userKey is null--设置Cookie 警告-[ remoteAddr:-"+request.getRemoteAddr()+"--requestDomain:-"+requestDomain+"---domain:-"+domain+"-]--------");
				out.println("invalid");
			}
			Ticket ticket=userTicketService.getTicket(userKey);
			logger.info("通过userKey["+userKey+"]获取ticket===>"+ticket);
			Cookie cookie=cookieService.getCookies(ticket);
			cookie.setMaxAge(3600*24*expireDay);
			if(!StringUtils.isEmpty(domain)){
				cookie.setDomain(domain);
			}
			response.addCookie(cookie);
			logger.info("-------设置Cookie 成功-[ ticket--"+ticket.getTicket()+"---remoteAddr:-"+request.getRemoteAddr()+"--requestDomain:-"+requestDomain+"--userKey:-"+userKey+"---domain:-"+domain+"-]--------");
			out.println("ok");
		} catch (Exception e) {
			logger.error("-------设置Cookie 异常-[  remoteAddr:-"+request.getRemoteAddr()+"--requestDomain:-"+requestDomain+"--userKey:-"+userKey+"---domain:-"+domain+"-]--------", e);
			out.println("invalid");
		}finally{
			if(out!=null){
				out.close();
			}
		}
	}
	
	/**
	 * 批量设置cookies
	 * @return
	 */
	@RequestMapping(value="/cookies.js")
	public void setCookies(String userKey,HttpServletResponse response){
		StringBuilder cookieJs=new StringBuilder();
		for(String cookieDomain:cookieDomains){ //域名后缀
			for(String serverDomain:serverDomains){ //域名
				//如果为IP地址[端口]则可以写全部的域
				if(serverDomain.matches("(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)(:\\d{2,5})?")){
					cookieJs.append("<script type=\"text/javascript\"");
					cookieJs.append("src=\"http://"+serverDomain+"/set-cookie.js?d="+System.currentTimeMillis()+"&userKey="+userKey+"&domain="+cookieDomain+"\">");
					cookieJs.append("</script>");
				}else if(serverDomain.endsWith(cookieDomain)){ //如果服务的域名的后缀域给定的后缀相同
					cookieJs.append("<script type=\"text/javascript\"");
					cookieJs.append("src=\"http://"+serverDomain+"/set-cookie.js?d="+System.currentTimeMillis()+"&userKey="+userKey+"&domain="+cookieDomain+"\">");
					cookieJs.append("</script>");
				}
			}
		}
		PrintWriter out=null;
		try {
			out=response.getWriter();
			out.print(cookieJs);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				out.close();
			}
		}
	}
	
	
	/**
	 * 批量删除cookies
	 * @return
	 */
	@RequestMapping(value="/batch-del-cookies.js")
	public void setCookies(HttpServletResponse response){
		StringBuilder cookieJs=new StringBuilder();
		for(String cookieDomain:cookieDomains){ //域名后缀
			for(String serverDomain:serverDomains){ //域名
				//如果为IP地址[端口]则可以写全部的域
				if(serverDomain.matches("(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)(:\\d{2,5})?")){
					cookieJs.append("<script type=\"text/javascript\"");
					cookieJs.append("src=\"http://"+serverDomain+"/del-cookie.js?d="+System.currentTimeMillis()+"&domain="+cookieDomain+"\">");
					cookieJs.append("</script>");
				}else if(serverDomain.endsWith(cookieDomain)){ //如果服务的域名的后缀域给定的后缀相同
					cookieJs.append("<script type=\"text/javascript\"");
					cookieJs.append("src=\"http://"+serverDomain+"/del-cookie.js?d="+System.currentTimeMillis()+"&domain="+cookieDomain+"\">");
					cookieJs.append("</script>");
				}
			}
		}
		PrintWriter out=null;
		try {
			out=response.getWriter();
			out.print(cookieJs);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				out.close();
			}
		}
	}
}
